<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车功能调试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-box {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin: 20px 0;
        }
        .status {
            font-size: 18px;
            margin: 20px 0;
            padding: 15px;
            border-radius: 5px;
        }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px;
        }
        button:hover { background: #0056b3; }
        pre {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            text-align: left;
            overflow-x: auto;
            margin: 10px 0;
        }
        .cart-item {
            border: 1px solid #ddd;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
            background: #f9f9f9;
        }
        .cart-item h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .cart-item p {
            margin: 5px 0;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="test-box">
        <h1>🛒 购物车功能调试</h1>
        
        <div id="status" class="status info">
            点击下方按钮测试购物车功能
        </div>
        
        <button onclick="testAddToCart()">添加商品到购物车</button>
        <button onclick="testGetCart()">获取购物车</button>
        <button onclick="testUpdateQuantity()">更新商品数量</button>
        <button onclick="testRemoveItem()">删除商品</button>
        
        <div id="result"></div>
    </div>

    <div class="test-box">
        <h2>🛒 购物车内容</h2>
        <div id="cartContent">
            <div class="info">点击"获取购物车"查看内容</div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:8080';
        let currentCartItems = [];
        
        async function testAddToCart() {
            const statusDiv = document.getElementById('status');
            const resultDiv = document.getElementById('result');
            
            statusDiv.className = 'status info';
            statusDiv.textContent = '正在添加商品到购物车...';
            resultDiv.innerHTML = '';
            
            try {
                const cartData = {
                    userId: 1002, // 使用测试用户ID
                    factoryId: 1, // 使用测试工厂ID
                    quantity: 2
                };
                
                console.log('发送购物车数据:', cartData);
                
                const response = await fetch(`${API_BASE_URL}/cart/add`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(cartData)
                });
                
                const data = await response.json();
                console.log('添加购物车响应:', data);
                
                if (data.code === '1') {
                    statusDiv.className = 'status success';
                    statusDiv.textContent = '✅ 商品添加成功！';
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                } else {
                    statusDiv.className = 'status error';
                    statusDiv.textContent = `❌ 添加失败: ${data.message}`;
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                }
            } catch (error) {
                statusDiv.className = 'status error';
                statusDiv.textContent = '❌ 添加请求失败';
                resultDiv.innerHTML = `<pre>${error.message}</pre>`;
            }
        }
        
        async function testGetCart() {
            const statusDiv = document.getElementById('status');
            const resultDiv = document.getElementById('result');
            const cartContentDiv = document.getElementById('cartContent');
            
            statusDiv.className = 'status info';
            statusDiv.textContent = '正在获取购物车...';
            resultDiv.innerHTML = '';
            cartContentDiv.innerHTML = '<div class="info">正在加载...</div>';
            
            try {
                const response = await fetch(`${API_BASE_URL}/cart/user/1002`);
                const data = await response.json();
                console.log('获取购物车响应:', data);
                
                if (data.code === '1') {
                    statusDiv.className = 'status success';
                    statusDiv.textContent = '✅ 购物车获取成功！';
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                    
                    // 显示购物车内容
                    const cartItems = data.obj?.cartItems || [];
                    currentCartItems = cartItems;
                    
                    if (cartItems.length === 0) {
                        cartContentDiv.innerHTML = '<div class="info">购物车为空</div>';
                    } else {
                        let html = '<h3>购物车商品：</h3>';
                        cartItems.forEach((item, index) => {
                            html += `
                                <div class="cart-item">
                                    <h4>商品 ${index + 1}</h4>
                                    <p><strong>ID:</strong> ${item.cid}</p>
                                    <p><strong>工厂名称:</strong> ${item.factoryName || '未知'}</p>
                                    <p><strong>工厂图片:</strong> ${item.factoryImage || '无'}</p>
                                    <p><strong>数量:</strong> ${item.quantity}</p>
                                    <p><strong>单价:</strong> ¥${item.pricePerUnit || 0}</p>
                                    <p><strong>总价:</strong> ¥${item.totalPrice || 0}</p>
                                    <p><strong>状态:</strong> ${item.status || '未知'}</p>
                                    <p><strong>选中:</strong> ${item.selected ? '是' : '否'}</p>
                                </div>
                            `;
                        });
                        cartContentDiv.innerHTML = html;
                    }
                } else {
                    statusDiv.className = 'status error';
                    statusDiv.textContent = `❌ 获取失败: ${data.message}`;
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                    cartContentDiv.innerHTML = '<div class="error">获取购物车失败</div>';
                }
            } catch (error) {
                statusDiv.className = 'status error';
                statusDiv.textContent = '❌ 获取请求失败';
                resultDiv.innerHTML = `<pre>${error.message}</pre>`;
                cartContentDiv.innerHTML = '<div class="error">请求失败</div>';
            }
        }
        
        async function testUpdateQuantity() {
            if (currentCartItems.length === 0) {
                alert('请先获取购物车内容');
                return;
            }
            
            const statusDiv = document.getElementById('status');
            const resultDiv = document.getElementById('result');
            
            const firstItem = currentCartItems[0];
            const newQuantity = prompt(`请输入新的数量 (当前: ${firstItem.quantity}):`, firstItem.quantity);
            
            if (!newQuantity || newQuantity < 1) {
                return;
            }
            
            statusDiv.className = 'status info';
            statusDiv.textContent = '正在更新商品数量...';
            resultDiv.innerHTML = '';
            
            try {
                const updateData = {
                    cid: firstItem.cid,
                    quantity: parseInt(newQuantity)
                };
                
                const response = await fetch(`${API_BASE_URL}/cart/update-quantity`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(updateData)
                });
                
                const data = await response.json();
                console.log('更新数量响应:', data);
                
                if (data.code === '1') {
                    statusDiv.className = 'status success';
                    statusDiv.textContent = '✅ 数量更新成功！';
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                    // 重新获取购物车
                    testGetCart();
                } else {
                    statusDiv.className = 'status error';
                    statusDiv.textContent = `❌ 更新失败: ${data.message}`;
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                }
            } catch (error) {
                statusDiv.className = 'status error';
                statusDiv.textContent = '❌ 更新请求失败';
                resultDiv.innerHTML = `<pre>${error.message}</pre>`;
            }
        }
        
        async function testRemoveItem() {
            if (currentCartItems.length === 0) {
                alert('请先获取购物车内容');
                return;
            }
            
            const statusDiv = document.getElementById('status');
            const resultDiv = document.getElementById('result');
            
            const firstItem = currentCartItems[0];
            if (!confirm(`确定要删除商品 "${firstItem.factoryName}" 吗？`)) {
                return;
            }
            
            statusDiv.className = 'status info';
            statusDiv.textContent = '正在删除商品...';
            resultDiv.innerHTML = '';
            
            try {
                const response = await fetch(`${API_BASE_URL}/cart/item/${firstItem.cid}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                console.log('删除商品响应:', data);
                
                if (data.code === '1') {
                    statusDiv.className = 'status success';
                    statusDiv.textContent = '✅ 商品删除成功！';
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                    // 重新获取购物车
                    testGetCart();
                } else {
                    statusDiv.className = 'status error';
                    statusDiv.textContent = `❌ 删除失败: ${data.message}`;
                    resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                }
            } catch (error) {
                statusDiv.className = 'status error';
                statusDiv.textContent = '❌ 删除请求失败';
                resultDiv.innerHTML = `<pre>${error.message}</pre>`;
            }
        }
    </script>
</body>
</html>
